#!/usr/bin/python

#
# Copyright 2008 Amit Shrestha
#

'''
This file is part of Words.

Words is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Words is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
'''

import re

from java.net import Socket
from java.io import PrintWriter
from java.io import BufferedReader
from java.io import OutputStreamWriter
from java.io import InputStreamReader

def __beautify_header(definition):
    splits = [x.strip() for x in definition.split('"')]
    out = '<b>From : ' + splits[3] + '</b>\n'
    return out

def __change_known_words_into_links(definition):
    finds = re.findall(r'\{(.*?)\}',definition)
    for x in finds:
        definition = re.sub('\{\s*' + x + '\s*\}','<a href="' + x + '">' + x + '</a>',definition)
    return definition

def get_definitions(word,hostname='www.dict.org',port=2628):
    sock = Socket(hostname,port)
    writer = PrintWriter(OutputStreamWriter(sock.getOutputStream(),"UTF-8"),True)
    reader = BufferedReader(InputStreamReader(sock.getInputStream(),"UTF-8"))

    reader.readLine() #banner

    writer.println("define * " + word)

    (rc,text) = reader.readLine().strip().split(' ',1)

    if int(rc) == 552:
        return ["No definitions found."]
    elif int(rc) != 150:
        return ["An error occured communicating with dict.org"]
    else:
        definitions = []
        while True:
            (rc,text) = reader.readLine().strip().split(' ',1)
            if int(rc) != 151:
                break
            
            definition = __beautify_header(text)
            while True:
                line = reader.readLine().strip()
                if line == ".":
                    break
                else: definition += line + "\n"
            definitions.append(__change_known_words_into_links(definition))
        return definitions
    reader.close()
    writer.close()
    sock.close()
